<template>
  <div>
    <nav-bar>
      <template v-slot:center>
        <span style="font-size: 0.16rem; color: #fff">个人中心</span>
      </template>
    </nav-bar>
    <div class="userInfo">
      <img :src="userInfo.avatar_url" alt="" v-if="userInfo.avatar_url" />
      <div>
        <p>
          <span>昵称：</span><span>{{ userInfo.name }}</span>
        </p>
        <p>
          <span>登录名：</span><span>{{ userInfo.email }}</span>
        </p>
        <p><span>个性签名:</span><span>11111</span></p>
      </div>
    </div>
    <div>
      <van-cell :title="item.title" is-link v-for="item in menu" :key="item.title" @click="goTo(item.path)" />
    </div>
    <van-button round block native-type="submit" class="btn" color="#42b983" style="margin-top: 20px" @click="onLogout"
      >退出登录</van-button
    >
  </div>
</template>

<script>
import { Toast } from 'vant'
import { userLogout, getUserInfo } from 'network/user'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { reactive, ref } from 'vue'
export default {
  name: 'Profile',
  setup() {
    // 生成vuex实例
    const store = useStore()
    // 生成路由实例
    const router = useRouter()
    // 功能菜单
    let menu = reactive([
      { title: '我的收藏', path: '/collect' },
      { title: '我的订单', path: '/order' },
      { title: '帐号管理', path: 'setting' },
      { title: '地址管理', path: 'address' },
      { title: '关于我们', path: '/about' }
    ])
    // 用户数据
    let userInfo = ref({})

    // 初始化数据的方法
    const init = async () => {
      const res = await getUserInfo()
      userInfo.value = res
    }
    init()
    // 点击退出按钮执行的回调
    function onLogout() {
      userLogout().then(res => {
        if (res.status === 204) {
          Toast.success('退出成功！')
          router.push('/login')
          // 删除token
          localStorage.removeItem('token')
          // 将Vuex中的状态修改成false
          store.commit('login/SETISLOGIN', false)
          store.commit('cart/RESETNUM')
        }
      })
    }
    // 路由跳转相关的回调
    function goTo(path) {
      console.log(path)
      router.push(path)
    }
    return {
      onLogout,
      menu,
      userInfo,
      goTo
    }
  }
}
</script>

<style lang="scss" scoped>
.userInfo {
  width: 95vw;
  height: 1.5rem;
  margin: 0.1rem auto;
  border-radius: 0.2rem;
  background: linear-gradient(to right, #42b983, #42bbaa);
  display: flex;
  padding: 0.1rem;
  align-items: center;
  img {
    height: 1rem;
    width: 1rem !important;
  }
  div {
    margin-left: 0.1rem;
    display: flex;
    flex-direction: column;
    height: 0.8rem;
    p {
      flex: 1;
      color: #fff;
    }
  }
}
</style>